package com.weitu.permission.user.controller;

import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.user.entity.User;
import com.weitu.permission.user.entity.UserDepartment;
import com.weitu.permission.user.entity.UserDuty;
import com.weitu.permission.user.entity.UserInfo;
import com.weitu.permission.user.service.UserService;
import com.weitu.plugin.PageView;
import com.weitu.shiro.helper.PasswordHelper;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/3/13
 */
@Controller
@RequestMapping(value = "permission/user")
public class UserController extends BaseController {

    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "permission/user";
    private static final String DEFAULT_PASSWORD = "123456";
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return MODULE_BATH_PATH + "/list";
    }

    @RequestMapping(value = "/simpleList", method = RequestMethod.GET)
    public String simpleList() {
        return MODULE_BATH_PATH + "/simpleList";
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);

        int count = this.userService.queryCount(paramMap);//获取列表总数量
        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象

        //未传sort参数是采用添加时间排序
        if (paramMap.get("sort") == null) {
            pageView.setSortColumn("addTime");
        }
        paramMap.put("pageView", pageView);

        List<User> dataList = this.userService.queryList(paramMap);//获取列表数据
        return dataGridPagination.flushDataGridData(dataList);
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add() {
        return MODULE_BATH_PATH + "/add";
    }

    @SystemLog(module = "用户管理", methods = "添加用户")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResult addAjax(User user) throws Exception{
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();

        putParametersIntoMap(paramMap);

        String id = IDGenerator.getId();
        String name = paramMap.get("name").toString();
        String deptId = paramMap.get("deptId").toString();

        if (userService.selectByUserName(name) != null) {
            result.setMessage("用户名已存在！");
            result.setSuccess(false);
            return result;
        }
        PasswordHelper helper = new PasswordHelper();
        helper.encryptPassword(user.getName(), DEFAULT_PASSWORD);

        user.setId(id);
        user.setPassword(helper.getEncPassword());
        user.setCredentialsSalt(helper.getCredentialsSalt());
        user.setAddTime(DateTimeUtil.formatterDateTime());
        user.setUpdateTime(DateTimeUtil.formatterDateTime());

        UserDepartment userDepartment = new UserDepartment();
        userDepartment.setUserId(id);
        userDepartment.setDeptId(deptId);
        // 关联基本信息
        user.getUserInfo().setId(IDGenerator.getId());
        user.getUserInfo().setUserId(id);

        int count;

        //有职位的时候保存用户职位关联表
        if (paramMap.get("dutyId") != null) {
            String dutyId = paramMap.get("dutyId").toString();
            UserDuty userDuty = new UserDuty();
            userDuty.setDeptId(deptId);
            userDuty.setUserId(id);
            userDuty.setDutyId(dutyId);
            count = this.userService.insertUserAndAssociation(user, userDepartment, userDuty);
            if (count == 3) {
                result.setMessage("保存成功！");
                result.setSuccess(true);
                return result;
            } else {
                result.setMessage("保存失败！");
                result.setSuccess(false);
                return result;
            }
        } else {
            count = this.userService.insertUserAndAssociation(user, userDepartment);//受影响的行数
            if (count == 2) {
                result.setMessage("保存成功！");
                result.setSuccess(true);
                return result;
            } else {
                result.setMessage("保存失败！");
                result.setSuccess(false);
                return result;
            }
        }
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, String id) {
        User user = userService.selectById(id);

        //有职位时拼接所有职位字符串
        if (user.getUserDutyList().size() > 0) {
            String duties = "";
            for (UserDuty userDuty : user.getUserDutyList()) {
                duties += "," + userDuty.getDeptId() + "-" + userDuty.getDutyId();
            }
            duties = duties.substring(1);
            model.addAttribute("duties", duties);
        }

        model.addAttribute(user);
        return MODULE_BATH_PATH + "/edit";
    }

    @SuppressWarnings("unchecked")
    @SystemLog(module = "用户管理", methods = "修改用户")
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public AjaxResult editAjax(User user) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult success = new AjaxResult("编辑成功!", true);
        AjaxResult fail = new AjaxResult("编辑失败!", false);

        putParametersIntoMap(paramMap);

        user.setUpdateTime(DateTimeUtil.formatterDateTime());

        // 关联基本信息
        user.getUserInfo().setId(IDGenerator.getId());
        user.getUserInfo().setUserId(user.getId());


        //未获取到职位参数,直接更新用户信息
        if (paramMap.get("dutyId") == null) {
            if (userService.updateByIdSelective(user)) {
                return success;
            } else {
                return fail;
            }
        }

        //获取到单个职位为string
        if (paramMap.get("dutyId") instanceof String) {
            //职位id为空时删除用户职位关联数据
            String dutyIdStr = (String) paramMap.get("dutyId");
            if (StringUtils.isEmpty(dutyIdStr)) {
                userService.deleteUserDutyByUserId(user.getId());
                if (userService.updateByIdSelective(user)) {
                    return success;
                } else {
                    return fail;
                }
            }

            if (updateSingleDuty(user, dutyIdStr) && userService.updateByIdSelective(user)) {
                return success;
            } else {
                return fail;
            }
        } else {//多个职位为list
            List<String> dutyIdList = (List<String>) paramMap.get("dutyId");
            if (updateMultipleDuty(user, dutyIdList) && userService.updateByIdSelective(user)) {
                return success;
            } else {
                return fail;
            }
        }
    }

    @SystemLog(module = "用户管理", methods = "删除用户")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult deleteAjax(String id) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();

        putParametersIntoMap(paramMap);

        int count = this.userService.deleteById(id);//受影响的行数

        if (count > 0) {
            result.setMessage("删除成功！");
            result.setSuccess(true);
            return result;
        } else {
            result.setMessage("删除失败！");
            result.setSuccess(false);
            return result;
        }
    }

    @SystemLog(module = "用户管理", methods = "重置密码")
    @ResponseBody
    @RequestMapping(value = "/reset", method = RequestMethod.POST)
    public AjaxResult resetAjax(String name) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);

        User user = new User();
        PasswordHelper helper = new PasswordHelper();
        helper.encryptPassword(name, DEFAULT_PASSWORD);

        user.setName(name);
        user.setPassword(helper.getEncPassword());
        user.setCredentialsSalt(helper.getCredentialsSalt());
        user.setUpdateTime(DateTimeUtil.formatterDateTime());
        int count = this.userService.updatePassword(user);//受影响的行数

        if (count > 0) {
            return success("重置密码成功！");
        } else {
            return fail("重置密码失败！");
        }
    }

    @RequestMapping(value = "/move", method = RequestMethod.GET)
    public String move(Model model, String id) {
        User user = userService.selectById(id);
        model.addAttribute(user);
        return MODULE_BATH_PATH + "/move";
    }

    @SystemLog(module = "用户管理", methods = "移动用户")
    @ResponseBody
    @RequestMapping(value = "/move", method = RequestMethod.POST)
    public AjaxResult moveAjax() {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();

        putParametersIntoMap(paramMap);

        String id = (String) paramMap.get("id");
        boolean isAlreadyHave = false;//是否选择了原来已存在的部门
        String oldDeptId = (String) paramMap.get("oldDeptId");
        String newDeptId = (String) paramMap.get("newDeptId");
        String isKeep = (String) paramMap.get("isKeep");
        String isMoveAuthority = (String) paramMap.get("isMoveAuthority");
        User user = userService.selectById(id);

        for (UserDepartment userDept : user.getUserDepartmentList()) {
            if (userDept.getDeptId().equals(newDeptId)) {
                result.setMessage("不能移动至已有部门！");
                result.setSuccess(false);
                isAlreadyHave = true;
                break;
            }
        }
        if (isAlreadyHave) {
            return result;
        } else {
            //是否在原部门保留用户
            if ("1".equals(isKeep)) {
                int count = userService.insertUserDepartment(new UserDepartment(id, newDeptId));
                if (count == 1) {
                    result.setMessage("移动成功！");
                    result.setSuccess(true);
                    return result;
                } else {
                    result.setMessage("移动失败！");
                    result.setSuccess(false);
                    return result;
                }
            } else {
                int count = userService.updateUserDepartment(new UserDepartment(id, oldDeptId), newDeptId);
                if (count == 2) {
                    result.setMessage("移动成功！");
                    result.setSuccess(true);
                    return result;
                } else {
                    result.setMessage("移动失败！");
                    result.setSuccess(false);
                    return result;
                }
            }
        }
    }


    @RequestMapping(value = "/updatePassword", method = RequestMethod.GET)
    public ModelAndView updatePassword() {

        User user = getSessionUser();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name", user.getName());
        modelAndView.setViewName(MODULE_BATH_PATH + "/updatePassword");
        return modelAndView;
    }

    @SystemLog(module = "用户管理", methods = "修改密码")
    @ResponseBody
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public AjaxResult updatePasswordAjax(String name, String password, String newPassword) {
        // Map<String, Object> paramMap = new HashMap<String, Object>();

        AjaxResult result = new AjaxResult();

        String message;

        boolean success;

        // putParametersIntoMap(paramMap);

        PasswordHelper helper = new PasswordHelper();

        //根据用户名查询出当前用户的信息
        User currUser = this.userService.selectByName(name);
        //当前用户加密之后的密码
        String currEncPassWord = currUser.getPassword();
        //当前用户的加密盐
        String currSalt = currUser.getCredentialsSalt();

        //检验当前密码是否正确

        if (helper.checkPassword(password, currEncPassWord, currSalt, name)) {
            User user = new User();

            helper.encryptPassword(name, newPassword);

            user.setName(name);
            user.setPassword(helper.getEncPassword());
            user.setCredentialsSalt(helper.getCredentialsSalt());
            user.setUpdateTime(DateTimeUtil.formatterDateTime());
            int count = this.userService.updatePassword(user);//受影响的行数

            if (count > 0) {
                message = "修改密码成功！";
                success = true;
            } else {
                message = "修改密码失败！";
                success = false;
            }
        } else {
            message = "当前密码输入错误，请重新输入！";
            success = false;
        }
        result.setMessage(message);
        result.setSuccess(success);

        return result;
    }

    @RequestMapping(value = "/demo")
    public String demo() {
        return MODULE_BATH_PATH + "/demo";
    }

    //更新多个职位信息
    private boolean updateMultipleDuty(User user, List<String> dutyList) {
        int count = 0;
        userService.deleteUserDutyByUserId(user.getId());
        for (String deptIdAndDutyId : dutyList) {
            UserDuty userDuty = new UserDuty();
            userDuty.setDeptId(deptIdAndDutyId.split("-")[0]);
            userDuty.setUserId(user.getId());
            userDuty.setDutyId(deptIdAndDutyId.split("-")[1]);

            count += userService.insertUserDuty(userDuty);
        }
        return count == dutyList.size();
    }

    //更新单个职位信息
    private boolean updateSingleDuty(User user, String deptIdAndDutyId) {
        UserDuty userDuty = new UserDuty();
        userDuty.setDeptId(deptIdAndDutyId.split("-")[0]);
        userDuty.setUserId(user.getId());
        userDuty.setDutyId(deptIdAndDutyId.split("-")[1]);
        //删除用户原有的职位关联关系
        userService.deleteUserDutyByUserId(user.getId());
        //插入新的用户职位关联
        int count = userService.insertUserDuty(userDuty);

        return count > 0;
    }
}
